package com.colorlight.cloud.xm.entity.instructions;

import com.colorlight.cloud.common.exception.ParameterException;
import com.colorlight.cloud.common.model.ExceptionEnum;
import com.colorlight.cloud.xm.api.XmEntityScheduleActions;
import com.colorlight.cloud.xm.entity.enumerate.ParamIndexEnum;
import com.colorlight.iot.proto.xm.entity.XmEntity;
import com.colorlight.iot.proto.xm.instruction.XmInstruction;
import com.google.protobuf.ByteString;
import com.google.protobuf.InvalidProtocolBufferException;
import lombok.*;
import lombok.extern.slf4j.Slf4j;
import com.colorlight.cloud.xm.entity.po.*;
import java.io.Serializable;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author Demon
 * @description 设备属性设置
 * @date 22/3/2024  上午8:59
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
@Slf4j
public class ParamSet implements XmEntityScheduleActions {
	private InputMsg input;
	private OutputMsg output;
	
	@Override
	public ByteString objectConvertBytes() {
		XmInstruction.ParamSet.InputMsg.Builder inputMsg =
				XmInstruction.ParamSet.InputMsg.newBuilder();
		inputMsg.setParameter(this.getInput().getParameter().toProto());
		List<XmEntity.ParamIndexEnum> collect = this.getInput().getParamIndex().stream().map(ParamIndexEnum::toProto).collect(Collectors.toList());
		inputMsg.addAllParamIndex(collect);
		XmInstruction.ParamSet.Builder paramSet =
				XmInstruction.ParamSet.newBuilder();
		paramSet.setInput(inputMsg);
		return paramSet.build().toByteString();
	}
	
	@Override
	public ParamSet byteConvertObject(ByteString bytes) {
		XmInstruction.ParamSet paramSet = null;
		try {
			paramSet = XmInstruction.ParamSet.parseFrom(bytes);
		} catch (InvalidProtocolBufferException e) {
			log.error("", e);
		}
		if (Objects.isNull(paramSet)) {
			throw new ParameterException(ExceptionEnum.MSG_PARAMETER_EXCEPTION);
		}
		final OutputMsg outputMsg = new OutputMsg();
		outputMsg.setParameter(new Parameter().formProto(paramSet.getOutput().getParameter()));
		this.setOutput(outputMsg);
		return this;
	}
	
	@Data
	@NoArgsConstructor
	@AllArgsConstructor
	@Builder
	public static class InputMsg implements Serializable {
		/**
		 * 配置项的PB索引
		 * 配置项
		 */
		private List<ParamIndexEnum> paramIndex;
		private Parameter parameter;
	}
	
	@Data
	@NoArgsConstructor
	@AllArgsConstructor
	@Builder
	public static class OutputMsg implements Serializable {
		/**
		 * 配置项
		 */
		private Parameter parameter;
	}
	
	
}
